<?php
class SeriesComponent extends Object {
	var $components = array( 'Auth','Session','RequestHandler','Email');
	var $series = null; 
	public function initialize(&$controller) {
        $this->controller = $controller;
        $this->data = $controller->data;  
        
        App::import('Helper','time'); 
		$this->time = new TimeHelper();
    }

    public function get(){
    	if(is_array($this->_page())){			
			if(isset($this->page['Cms']['name'])){
				$this->controller->set('title_for_layout_cms',$this->page['Cms']['name']);
				$this->controller->set('keywords_for_layout_cms',$this->page['Cms']['keywords']);
				$this->controller->set('description_for_layout_cms',$this->page['Cms']['description']);
			
				if(!$this->_sections()){
					$this->controller->set('sections',$this->sections);
				}
			}
		}else{
			$this->controller->set('title_for_layout_cms',false);
			$this->controller->set('keywords_for_layout_cms',false);
			$this->controller->set('description_for_layout_cms',false);
		}   	
    }
    
	function close(){
		$this->close_all();
	}
	
	private function close_all(){
		App::import('Model','order'); 
		$this->Order = new Order();
		
		App::import('Model','order_series'); 
		$this->OrdersSeries = new OrdersSeries();		
		
		$orders_month = $this->Order->find('all',array('conditions'=>array(
			'OrdersCycle.type_of_cycle_id' => '1'
		)));
		$orders_week = $this->Order->find('all',array('conditions'=>array(
			'OrdersCycle.type_of_cycle_id' => '2'
		)));
		$orders_daily = $this->Order->find('all',array('conditions'=>array(
			'OrdersCycle.type_of_cycle_id' => '3'
		)));	
		$orders_once = $this->Order->find('all',array('conditions'=>array(
			'OrdersCycle.type_of_cycle_id' => '4'
		)));


		
		$date_start_ = $this->OrdersSeries->find('first',array('fields'=>
			array('MAX(OrdersSeries.execution_date) as execution_date')
		));
		$date_start_ = (is_array($date_start_) && isset($date_start_[0]['execution_date'])) ? $date_start_[0]['execution_date'] : date('Y').'-'.date('m').'-'.'01';
		 
		$date_start = new DateTime();
		$date_start->setDate($this->time->format('Y',$date_start_), $this->time->format('m',$date_start_), $this->time->format('d',$date_start_));
		$date_start->modify("+1 day");
		$date_start = $date_start->format('Y-m-d');
		
		$date_end = new DateTime();
		$date_end->setDate(date('Y'), date('m'), date('d'));
		$date_end->modify("-1 day");
		$date_end = $date_end->format('Y-m-d');
		if($date_start <= $date_end){
			$this->_monthly($orders_month, $date_start, $date_end);
			$this->_weekly($orders_week, $date_start, $date_end);
			$this->_daily($orders_daily, $date_start, $date_end);
			$this->_once($orders_once, $date_start, $date_end);
			if(is_array($this->series)){
				ksort($this->series);
				
				foreach ($this->series as $date => $employees){
					$seria = array();
					foreach ($employees as $employee_id => $employee){
						foreach ($employee['orders'] as $orders_id => $order){
							$seria['OrdersSeries']['employee_id'] = $employee_id;			
							$seria['OrdersSeries']['orders_id'] = $orders_id;
							$seria['OrdersSeries']['execution_date'] = $date;
							$seria['OrdersSeries']['salary'] = $order['Order']['value_of_the_order'];
							$seria['OrdersSeries']['payment_status'] = 2;
							$seria['OrdersSeries']['payment_numer'] = date('YmdHi');
							$seria['OrdersSeries']['status'] = 2;
							$seria['OrdersSeries']['orders_billing_id'] = 0; // wymagane 0
							if(!empty($order['Order']['OrdersEmployee']['percent'])){
								$seria['OrdersSeries']['employee_salary'] = ($seria['OrdersSeries']['salary']*$order['Order']['OrdersEmployee']['percent'])/100;
							}else if(!empty($order['Order']['OrdersEmployee']['amount'])){
								$seria['OrdersSeries']['employee_salary'] = $order['Order']['OrdersEmployee']['amount'];
							}else{
								$seria['OrdersSeries']['employee_salary'] = ($seria['OrdersSeries']['salary'] * 10 )/100;
								
							}
							$this->OrdersSeries->create();
							if(!$this->OrdersSeries->save($seria)){
								$this->Session->setFlash(__("Blad w naliczaniu i zamykaniu zlecenia", true));
							}
						}
					}
				}	
			}
		}
	}
	private function _monthly($orders_month,$date_start,$date_end){
					
		// for every orders check day
		foreach ($orders_month as $key => $order) {
			$miesiace = $this->_oblicz_miesiace($order['OrdersCycle']['date_start'],$date_end,$order['OrdersCycle']['repeat'] );
			$date_start__ = explode("-",$date_start);		
			$date_progres = new DateTime();
			$date_progres->setDate($date_start__[0], $date_start__[1], $date_start__[2]);
			
			$date_order_start = $this->time->format('Y-m-d',$order['OrdersCycle']['date_start']);
			$date_order_end = (!empty($order['OrdersCycle']['date_end'])) ? $this->time->format('Y-m-d',$order['OrdersCycle']['date_end']) : $date_end;
			
					
			while ($date_progres->format("Y-m-d") <= $date_end ) {	
							
				$day = $date_progres->format("j");
				$month = $date_progres->format("m");
				$year = $date_progres->format("Y");	
				if(
					$date_order_start <= $date_progres->format("Y-m-d")
					&& $date_order_end >= $date_progres->format("Y-m-d") 
					&& $order['OrdersCycle']['_'.$day] == 1
					&& array_key_exists($month.$year, $miesiace)
				){	
		
					$this->_save_array_orders($date_progres->format("Y-m-d"),$order);

				}
				$date_progres->modify("+1 day");
			}						
		}	
	}
	
	private function _weekly($orders_week,$date_start,$date_end){
				
		// for every orders check day
		foreach ($orders_week as $key => $order) {
			$weeks = $this->_oblicz_tygodnie($order['OrdersCycle']['date_start'],$date_end,$order['OrdersCycle']['repeat'] );
			$date_start__ = explode("-",$date_start);		
			$date_progres = new DateTime();
			$date_progres->setDate($date_start__[0], $date_start__[1], $date_start__[2]);
			
			$date_order_start = $this->time->format('Y-m-d',$order['OrdersCycle']['date_start']);
			$date_order_end = (!empty($order['OrdersCycle']['date_end'])) ? $this->time->format('Y-m-d',$order['OrdersCycle']['date_end']) : $date_end;
					
			while ($date_progres->format("Y-m-d") <= $date_end ) {	

				$nDay = $date_progres->format("N");
				$nWeek =$date_progres->format('W');

				if(
					$date_progres->format("Y-m-d") >= $date_order_start 
					&& $date_progres->format("Y-m-d") <= $date_order_end 
					&& $order['OrdersCycle']['_'.$nDay] == 1
					&& array_key_exists($nWeek, $weeks)
				){	
					$this->_save_array_orders($date_progres->format("Y-m-d"),$order);
				}
				$date_progres->modify("+1 day");
			}						
		}	
	}	
	
	private function _daily($orders_daily, $date_start, $date_end){
					
		// for every orders check day
		foreach ($orders_daily as $key => $order) {
			$dni = $this->_oblicz_dni($order['OrdersCycle']['date_start'],$date_end,$order['OrdersCycle']['repeat'] );
			$date_start__ = explode("-",$date_start);		
			$date_progres = new DateTime();
			$date_progres->setDate($date_start__[0], $date_start__[1], $date_start__[2]);

			$date_order_start = $this->time->format('Y-m-d',$order['OrdersCycle']['date_start']);			
			$date_order_end = (!empty($order['OrdersCycle']['date_end'])) ? $this->time->format('Y-m-d',$order['OrdersCycle']['date_end']) : $date_end;
			
			while ($date_progres->format("Y-m-d") <= $date_end ) {	
							
				$_day = $date_progres->format("j");
				$keyDay = $date_progres->format("dmY");
				
				if(
					$date_order_start <= $date_progres->format("Y-m-d")
					&& $date_order_end >= $date_progres->format("Y-m-d")
					&& array_key_exists($keyDay, $dni)
				){	
		
					$this->_save_array_orders($date_progres->format("Y-m-d"),$order);
				}
				$date_progres->modify("+1 day");
			}						
		}		
	}	
	
	private function _once($orders_once, $date_start, $date_end){
		if(is_array($orders_once) && !empty($orders_once)){
		
			// for every orders check day
			foreach ($orders_once as $key => $order) {
				$date_order = $this->time->format('Y-m-d',$order['OrdersCycle']['date_start']);
				
				if( $date_order >= $date_start && $date_order <= $date_end){
					$this->_save_array_orders($date_order,$order);
				}									
			}	
		}	
	}	
	
	private function _save_array_orders($date_progres,$order){
		foreach ($order['Employee'] as $key => $employee) {						
			// dodajemy dzien i dane zlecenia
			$this->series[$date_progres][$employee['id']]['emplo'] = $employee;
			$this->series[$date_progres][$employee['id']]['orders'][$order['Order']['id']]['Order'] = $order['Order'];
			$this->series[$date_progres][$employee['id']]['orders'][$order['Order']['id']]['OrdersEmployee'] = $employee['OrdersEmployee'];						
		}

	}
	
	private function _oblicz_miesiace($from, $to, $repeat=1){
		$repeat = (empty($repeat)) ? 1 :$repeat ;
		$dStart = new DateTime();
		$from_ = explode("-",$from);
		$dStart->setDate($from_[0], $from_[1], $from_[2]);
		$miesiace = array();
		while ($dStart->format("Y-m-d") <= $to) {
			$miesiace[$dStart->format("mY")]= $dStart->format("Y-m-d");
			$dStart->modify("+{$repeat} month");
		}
		return $miesiace;
	}
	private function _oblicz_tygodnie($from, $to, $repeat=1){
		$repeat = (empty($repeat)) ? 1 :$repeat ;
		
		$week_start = $this->time->format('W',$from);
		$week_end = $this->time->format('W',$to);		
		$weeks = array();
		while ($week_start <= $week_end ) {
			$weeks[$week_start] = $week_start;
			$week_start = $week_start + $repeat;
		}
		return $weeks;
	}	
	private function _oblicz_dni($from, $to, $repeat=1){
		$repeat = (empty($repeat)) ? 1 :$repeat ;
		$dStart = new DateTime();
		$from_ = explode("-",$from);
		$dStart->setDate($from_[0], $from_[1], $from_[2]);
		$dni = array();
		while ($dStart->format("Y-m-d") <= $to) {
			$dni[$dStart->format("dmY")] = $dStart->format("Y-m-d");
			$dStart->modify("+{$repeat} day");
		}
		return $dni;
	}	
}